﻿using HamcoWcs.Tools.Tibco.Entities;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace HamcoWcs.Tools.Tibco
{
    public partial class Program
    {


        private static void Main(string[] args)
        {

            Task.Run(() =>
            {
                while (true)
                {
                    MonitorMainProcess(null);
                    Thread.Sleep(1000);
                }
            });
            //Timer monitor = new Timer(MonitorMainProcess, null, 0, 1000);

            var context = new Context(SQLCLIENT);
            var tool = new TibcoTool(PrintSend, PrintRecv, PrintError, context);

            PRESS_KEY_QUIT();
            tool.Dispose();
        }

        static void MonitorMainProcess(object o)
        {
            var progress = Process.GetProcessesByName("HamcoWcs.Main");

            if (progress.Length == 0)
            {
                Console.WriteLine($"TibcoExchange Server:[WARNING],WCS main process is shutdown,TibcoExchange will auto close.");

                try
                {
                    SQLCLIENT.Insertable<SystemErrorLog>(new SystemErrorLog()
                    {
                        Log = $"TibcoExchange Server:[WARNING],WCS main process is shutdown,TibcoExchange will auto close.",
                        CreatedTime = DateTime.Now,
                    }).ExecuteCommand();
                }
                catch (Exception)
                {
                    Console.WriteLine("log error");
                }
                finally
                {
                    Process.GetCurrentProcess().Kill();
                }

            }
        }
    }
}